﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MedCenters : System.Web.UI.Page
{
    protected int CurrentPage;
    enum Sorting { ByTitle, ByDate, Views };

    int iCentersNum = 0;
    DataTable DTCenters;
    Sorting currentSorting;

    protected void Page_Load(object sender, EventArgs e)
    {
        GetCategories();

        if (!IsPostBack)
        {
            currentSorting = Sorting.ByTitle;
            GetData();
            txtKeywords.Text = PageHeaderData.GetPageKeywordsByType(NewsType.MedicalCenters);
            CategoryItem cat = Category.ItemById((int)NewsType.MedicalCenters);
            txtDescription.Text = cat.cDescription;
            txtBrowserTitle.Text = cat.cTitle;
        }

    }

    protected void btnAddKeywords_Click(Object sender, EventArgs e)
    {
        PageHeaderData.SetPageKeywords(NewsType.MedicalCenters, txtKeywords.Text);
        Dal.arParams.Clear();
        Dal.arParams.Add((int)NewsType.MedicalCenters);
        Dal.arParams.Add(txtBrowserTitle.Text);
        Dal.arParams.Add(txtDescription.Text);
        Dal.ExecuteDBsp("Admin_AddCategoryDescription", Dal.arParams, true);
    }

    private void GetCategories()
    {
        Dal.arParams.Clear();
        Dal.arParams.Add((int)NewsType.MedicalCenters);
        DTCenters = Dal.ExecuteDBsp("usp_GetCategoryByParent", Dal.arParams);
        if (DTCenters != null)
        {
            if (DTCenters.Rows.Count > 0)
            {
                iCentersNum=DTCenters.Rows.Count ;
                gvCenters.DataSource = DTCenters;
                gvCenters.DataBind();
            }
        }
    }

    protected void chkVisible_Changed(Object sender, EventArgs e)
    {
        Int32 iLinkID;
        string _val = ((CheckBox)sender).Attributes["CommandArgument"];
        Int32.TryParse(_val, out iLinkID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iLinkID);//PageSize
        Dal.arParams.Add(((CheckBox)sender).Checked);//Checked
        Dal.ExecuteDBsp("Admin_SetVisible", Dal.arParams);

        GetData();
    }

    protected void gvNews_Sorting(object sender, GridViewSortEventArgs e)
    {
        switch (e.SortExpression)
        {
            case "Title":
                currentSorting = Sorting.ByTitle;
                break;
            case "Date":
                currentSorting = Sorting.ByDate;
                break;
            case "Views":
                currentSorting = Sorting.Views;
                break;
        }
        GetData();
    }

    private void GetData()
    {
        ObjectDataSource ods = new ObjectDataSource();
        ods.ID = "ods" + 1;
        ods.EnablePaging = gvNews.AllowPaging; //the paging of ODS depends on the paging of the GridView
        ods.TypeName = "MyTableAdapter"; //be sure to prefix the namespace of your application !!! e.g. MyApp.MyTableAdapter

        ods.SelectMethod = "GetData";
        ods.SelectCountMethod = "VirtualItemCount";
        ods.StartRowIndexParameterName = "startRow";
        ods.MaximumRowsParameterName = "maxRows";
        ods.EnableViewState = false;

        ods.ObjectCreating += new ObjectDataSourceObjectEventHandler(ods_ObjectCreating);
        gvNews.DataSource = ods;
        gvNews.DataBind();

        //if (ddlPageNumber.Items.Count == 0 || GVTrivias.PageCount != ddlPageNumber.Items.Count)
        //{
        //    ddlPageNumber.Items.Clear();
        // for (int icount = 1; icount < gvNews.PageCount + 1; icount++)
        //   {
        ////        ListItem li = new ListItem(icount.ToString(), icount.ToString());
        ////        ddlPageNumber.Items.Add(li);
        //    }
        //    lblShowRecords.Text = string.Format(" {0} ", GVTrivias.PageCount);
        //}

    }

    private void ods_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        //calling a "parametered" constructor of my own TableAdapter and passing it to the ObjectInstance property 
        Dal.arParams.Clear();
        Dal.arParams.Add((int)NewsType.MedicalCenters);//CatID
        Dal.arParams.Add(CurrentPage);//Current Page
        Dal.arParams.Add(gvNews.PageSize);//PageSize
        Dal.arParams.Add((int)currentSorting);//PageSize
        DataSet DS = Dal.ExecuteDBspDS("Admin_GetCentersByCategoryWPaging", Dal.arParams);

        if (DS != null)
        {
            if (DS.Tables.Count > 0)
            {
                MyTableAdapter tAdapter = new MyTableAdapter(DS.Tables[0]);
                e.ObjectInstance = tAdapter;
            }

            //and that'all there's to it !!
        }
    }

    protected void gvCenters_ItemCommand(object source, CommandEventArgs e)
    {
        bool bChanged = false;
        Int32 rowID;
        Int32.TryParse(e.CommandArgument.ToString(), out rowID);
        Int32 rowIndex = 0;

        //if (Convert.ToBoolean(ViewState["pnlManageVisible"]))
        //{
        //    ViewState["pnlManageVisible"] = false;
        //    pnlManage.Controls.Clear();
        //    pnlManage.Style.Add("display", "none");
        //}
        if (DTCenters != null)
        {
            for (Int16 i = 0; i < DTCenters.Rows.Count; i++)
            {
                if (DTCenters.Rows[i]["ID"].Equals(rowID))
                {
                    rowIndex = i;
                    break;
                }
            }

            switch (e.CommandName)
            {
                case "MoveUp":
                    if (rowIndex > 0)
                    {
                        DTCenters.Rows[rowIndex - 1]["orderID"] = rowIndex;
                        DTCenters.Rows[rowIndex]["orderID"] = rowIndex - 1;
                        bChanged = true;
                    }
                    break;
                case "MoveDown":
                    if (rowIndex < DTCenters.Rows.Count - 1)
                    {
                        DTCenters.Rows[rowIndex + 1]["orderID"] = rowIndex;
                        DTCenters.Rows[rowIndex]["orderID"] = rowIndex + 1;
                        bChanged = true;
                    }
                    break;
            }
            if (bChanged)
            {
                string sXml = string.Empty;
                for (int iCount = 0; iCount < DTCenters.Rows.Count; iCount++)
                {
                    sXml += string.Format("<c id=\"{0}\" ord=\"{1}\"/>", DTCenters.Rows[iCount]["ID"], DTCenters.Rows[iCount]["orderID"]);
                }
                sXml = "<cs>" + sXml + "</cs>";

                Dal.arParams.Clear();
                Dal.arParams.Add(sXml);
                Dal.ExecuteDBsp("Admin_UpdateCategoriesOrderID", Dal.arParams);

            }
        }
        GetCategories();
        //Session["FilesOrder"] = dt;
    }

    protected void btnEditCenter_Click(Object sender, CommandEventArgs e)
    {
        Int32 i=gvCenters.SelectedIndex;
        //txtAddCategory.Text=DTCenters.Select("catid=" + e.CommandArgument)[0]["cTitle"].ToString();
        hfCatID.Value=DTCenters.Select("catid=" + e.CommandArgument)[0]["catID"].ToString();
        
        CategoryItem cItem=Category.ItemById(Convert.ToInt32(hfCatID.Value));
        txtAddCategory.Text=cItem.cTitle;
        txtcatDescription.Text = cItem.cDescription;
        txtCatKeywords.Text = PageHeaderData.GetPageKeywordsByCatID(cItem.catId);
    }

    protected void btnDeleteCenter_Click(Object sender, CommandEventArgs e)
    {
        Int32 iCategoryID;
        Int32.TryParse(e.CommandArgument.ToString(), out iCategoryID);
        Dal.arParams.Clear();
        Dal.arParams.Add(iCategoryID);

        Dal.ExecuteDBsp("Admin_DeleteCategory", Dal.arParams);
        GetCategories();
    }

    protected void btnAddCategory_Click(Object sender ,EventArgs e)
    {
        Int32 iCategoryID;
        Int32.TryParse(hfCatID.Value, out iCategoryID);

        string sText = txtAddCategory.Text;
        Dal.arParams.Clear();
        Dal.arParams.Add(iCategoryID);
        Dal.arParams.Add((int)NewsType.MedicalCenters); // med centers
        Dal.arParams.Add(sText);
        Dal.arParams.Add(txtcatDescription.Text); // description
        Dal.arParams.Add(ab.ConvertToEnglishText(sText));
        Dal.arParams.Add(iCentersNum+1);
        Dal.ExecuteDBsp("Admin_AddCategory", Dal.arParams,true);
        PageHeaderData.SetPageKeywordsForCatID(iCategoryID, txtCatKeywords.Text);

        GetCategories();
        txtAddCategory.Text = string.Empty;
        txtCatKeywords.Text = string.Empty;
        txtcatDescription.Text = string.Empty;


    }

    protected void btnDeleteNews_Click(Object sender, CommandEventArgs e)
    {
        Int32 iLinkID;
        Int32.TryParse(e.CommandArgument.ToString(), out iLinkID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iLinkID);
        Dal.ExecuteDBsp("Admin_DeleteArticle", Dal.arParams);
        GetData();
    }

    protected void btnEditNews_Click(Object sender, CommandEventArgs e)
    {
        Int32 iLinkID;

        Int32.TryParse(e.CommandArgument.ToString(), out iLinkID);

        Response.Redirect("Addarticle.aspx?id=" + iLinkID);
    }

    // ConfirmDelete
    protected void gvCenters_RowBound(object sender, GridViewRowEventArgs e)
    {
        AjaxControlToolkit.ConfirmButtonExtender cb = new AjaxControlToolkit.ConfirmButtonExtender();
        try
        {
            cb.TargetControlID = e.Row.FindControl("btnDeleteCenter").ClientID.Replace("_", "$");
            cb.OnClientCancel = "CancelClick";
            cb.ConfirmText = "Вы уверены , что хотите удалить запись ?";
            e.Row.Cells[1].Controls.Add(cb);
        }
        catch { }
    }

    protected void gvNews_RowBound(object sender, GridViewRowEventArgs e)
    {
        AjaxControlToolkit.ConfirmButtonExtender cb = new AjaxControlToolkit.ConfirmButtonExtender();
        try
        {
            cb.TargetControlID = e.Row.FindControl("btnDeleteNews").ClientID.Replace("_", "$");
            cb.OnClientCancel = "CancelClick";
            cb.ConfirmText = "Вы уверены , что хотите удалить запись ?";
            e.Row.Cells[5].Controls.Add(cb);
        }
        catch { }
    }
}
